<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>惠农通 - 订单管理</title>
    <link rel="icon" href="./assets/logo.ico" type="images/x-ico" />
    <link rel="stylesheet" href="css/main.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* 订单管理页面特定样式 */
        .action-btn {
            padding: 4px 8px;
            margin: 0 4px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s;
        }
        
        .action-btn i {
            margin-right: 4px;
        }
        
        .edit-btn {
            background-color: #e6f7ff;
            color: #1890ff;
        }
        
        .edit-btn:hover {
            background-color: #bae7ff;
        }
        
        .delete-btn {
            background-color: #fff1f0;
            color: #f5222d;
        }
        
        .delete-btn:hover {
            background-color: #ffccc7;
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-0 {
            background-color: #fff7e6;
            color: #fa8c16;
        }
        
        .status-1 {
            background-color: #f6ffed;
            color: #52c41a;
        }
        
        /* 图片预览样式 */
        .order-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
            border: 1px solid #eee;
            transition: transform 0.3s;
        }
        
        .order-image:hover {
            transform: scale(1.8);
            z-index: 10;
            position: relative;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        /* 图片上传区域 */
        .image-upload-container {
            margin-bottom: 16px;
        }
        
        .image-upload-wrapper {
            display: flex;
            align-items: center;
            gap: 16px;
        }
        
        .image-preview {
            width: 100px;
            height: 100px;
            border: 1px dashed #d9d9d9;
            border-radius: 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            overflow: hidden;
            position: relative;
        }
        
        .image-preview img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
        }
        
        .upload-btn-wrapper {
            position: relative;
            overflow: hidden;
            display: inline-block;
        }
        
        .upload-btn {
            border: 1px solid #1890ff;
            color: #1890ff;
            background-color: #fff;
            padding: 6px 12px;
            border-radius: 4px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .upload-btn:hover {
            background-color: #e6f7ff;
        }
        
        .upload-btn-wrapper input[type=file] {
            font-size: 100px;
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            cursor: pointer;
        }
        
        .upload-tip {
            font-size: 12px;
            color: #999;
            margin-top: 8px;
        }
        
        /* 表格调整 */
        #orderTable th:nth-child(1),
        #orderTable td:nth-child(1) {
            width: 5%;
        }
        
        #orderTable th:nth-child(2),
        #orderTable td:nth-child(2) {
            width: 15%;
        }
        
        /* 模态框调整 */
        .modal-dialog {
            max-width: 600px;
        }
        
        .form-row {
            display: flex;
            gap: 16px;
            margin-bottom: 16px;
        }
        
        .form-group {
            flex: 1;
        }
    </style>
</head>
<body>
<div class="admin-container">
    <!-- 侧边栏 -->
    <aside class="sidebar">
        <div class="sidebar-header">
            <div class="logo">
                <img src="assets/logo.png" alt="惠农通">
                <h2>惠农通</h2>
            </div>
        </div>
        <nav class="sidebar-menu">
            <ul>
                <li data-page="dashboard">
                    <i class="fas fa-chart-line"></i>
                    <span>数据概览</span>
                </li>
                <li data-page="employees">
                    <i class="fas fa-users"></i>
                    <span>员工管理</span>
                </li>
                <li data-page="expert">
                    <i class="fas fa-user-tie"></i>
                    <span>专家管理</span>
                </li>
                <li  data-page="farm-management">
                    <i class="fas fa-warehouse"></i>
                    <span>农场管理</span>
                </li>
                <li data-page="product">
                    <i class="fas fa-box-open"></i>
                    <span>产品管理</span>
                </li>
                <li class="active" data-page="order">
                    <i class="fas fa-shopping-cart"></i>
                    <span>订单管理</span>
                </li>
                <li data-page="ai-chat">
                    <i class="fas fa-robot"></i>
                    <span>AI问答</span>
                </li>
                <li data-page="activities">
                    <i class="fas fa-tractor"></i>
                    <span>农业活动</span>
                </li>
                <li data-page="settings">
                    <i class="fas fa-cog"></i>
                    <span>系统设置</span>
                </li>
            </ul>
        </nav>
        <div class="sidebar-footer">
            <button class="logout-btn" id="logoutBtn">
                <i class="fas fa-sign-out-alt"></i>
                <span>退出登录</span>
            </button>
        </div>
    </aside>

    <!-- 主内容区 -->
    <main class="main-content">
        <header class="main-header">
            <h1 id="pageTitle">订单管理</h1>
            <div class="user-info">
                <span class="welcome">欢迎，<span id="currentUser">管理员</span></span>
                <div class="avatar">
                    <i class="fas fa-user-circle"></i>
                </div>
            </div>
        </header>

        <!-- 订单管理页面 -->
        <div id="ordersPage" class="page-content">
            <div class="page-toolbar">
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" id="searchOrderName" placeholder="输入产品名称搜索">
                    <button class="search-btn" id="searchOrderBtn">搜索</button>
                </div>
                <button class="primary-btn" id="addOrderBtn">
                    <i class="fas fa-plus"></i> 新增订单
                </button>
            </div>

            <div class="table-container">
                <table id="orderTable">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>产品图片</th>
                        <th>产品名称</th>
                        <th>商家名称</th>
                        <th>用户ID</th>
                        <th>数量</th>
                        <th>单价</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody></tbody>
                </table>
                <div class="loading-overlay" id="orderLoading">
                    <div class="spinner"></div>
                    <span>加载中...</span>
                </div>
            </div>

            <div class="pagination-wrapper">
                <div class="pagination-controls">
                    <button class="page-btn" id="prevOrderPageBtn">
                        <i class="fas fa-chevron-left"></i> 上一页
                    </button>
                    <span class="page-info" id="currentOrderPage"></span>
                    <button class="page-btn" id="nextOrderPageBtn">
                        下一页 <i class="fas fa-chevron-right"></i>
                    </button>
                    <select class="page-select" id="orderPageSize">
                        <option value="10">每页10条</option>
                        <option value="20">每页20条</option>
                        <option value="50">每页50条</option>
                    </select>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- 订单表单模态框 -->
<div id="orderModal" class="modal">
    <div class="modal-dialog">
        <div class="modal-header">
            <h3 id="orderModalTitle">新增订单</h3>
            <button class="close-btn" id="closeOrderModalBtn">&times;</button>
        </div>
        <form id="orderForm" class="modal-body">
            <input type="hidden" id="orderId">
            <input type="hidden" id="picture">
            
            <div class="image-upload-container">
                <label>产品图片</label>
                <div class="image-upload-wrapper">
                    <div class="image-preview" id="imagePreview">
                        <i class="fas fa-image" style="font-size: 24px; color: #ccc;"></i>
                    </div>
                    <div class="upload-btn-wrapper">
                        <button type="button" class="upload-btn" id="uploadBtn">
                            <i class="fas fa-upload"></i> 选择图片
                        </button>
                        <input type="file" id="imageUpload" accept="image/*">
                    </div>
                </div>
                <div class="upload-tip">建议上传1:1比例的图片，大小不超过2MB</div>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label for="modalProductName">产品名称</label>
                    <input type="text" id="modalProductName" placeholder="输入产品名称" required>
                </div>
                <div class="form-group">
                    <label for="modalStoreName">商家名称</label>
                    <input type="text" id="modalStoreName" placeholder="输入商家名称" required>
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label for="modalUserId">用户ID</label>
                    <input type="text" id="modalUserId" placeholder="输入用户ID" required>
                </div>
                <div class="form-group">
                    <label for="modalType">产品型号</label>
                    <input type="text" id="modalType" placeholder="输入产品型号" required>
                </div>
            </div>
            
            <div class="form-row">
                <div class="form-group">
                    <label for="modalNumber">购买数量</label>
                    <input type="number" id="modalNumber" min="1" value="1" required>
                </div>
                <div class="form-group">
                    <label for="modalPrice">产品单价</label>
                    <input type="number" id="modalPrice" min="0" step="0.01" placeholder="0.00" required>
                </div>
            </div>
            
            <div class="form-group">
                <label for="modalAddress">收货地址</label>
                <input type="text" id="modalAddress" placeholder="输入收货地址" required>
            </div>
            
            <div class="form-group">
                <label for="modalStatus">订单状态</label>
                <select id="modalStatus" class="form-control">
                    <option value="0">未完成</option>
                    <option value="1">已完成</option>
                </select>
            </div>
            
            <div class="form-actions">
                <button type="button" class="secondary-btn" id="cancelOrderModalBtn">
                    <i class="fas fa-times"></i> 取消
                </button>
                <button type="submit" class="primary-btn">
                    <i class="fas fa-save"></i> 保存
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    // 基础URL配置
    const BASE_URL = 'http://192.168.8.128:8080';
    // OSS上传接口URL
    const OSS_UPLOAD_URL = `${BASE_URL}/upload`;
    
    document.addEventListener('DOMContentLoaded', function() {
        // 全局变量
        let currentOrderPage = 1;
        let pageSize = 10;
        let searchKeyword = '';
        const token = localStorage.getItem('token');
        
        // DOM元素
        const orderTable = document.getElementById('orderTable').getElementsByTagName('tbody')[0];
        const loadingOverlay = document.getElementById('orderLoading');
        const prevPageBtn = document.getElementById('prevOrderPageBtn');
        const nextPageBtn = document.getElementById('nextOrderPageBtn');
        const currentPageSpan = document.getElementById('currentOrderPage');
        const pageSizeSelect = document.getElementById('orderPageSize');
        const searchInput = document.getElementById('searchOrderName');
        const searchBtn = document.getElementById('searchOrderBtn');
        const addOrderBtn = document.getElementById('addOrderBtn');
        const orderModal = document.getElementById('orderModal');
        const closeModalBtn = document.getElementById('closeOrderModalBtn');
        const cancelModalBtn = document.getElementById('cancelOrderModalBtn');
        const orderForm = document.getElementById('orderForm');
        const modalTitle = document.getElementById('orderModalTitle');
        const imageUpload = document.getElementById('imageUpload');
        const imagePreview = document.getElementById('imagePreview');
        const pictureInput = document.getElementById('picture');
        
        // 侧边栏菜单项
        const menuItems = document.querySelectorAll('.sidebar-menu li');
        
        // 初始化页面
        initPage();
        
        // 事件监听
        prevPageBtn.addEventListener('click', goToPrevPage);
        nextPageBtn.addEventListener('click', goToNextPage);
        pageSizeSelect.addEventListener('change', changePageSize);
        searchBtn.addEventListener('click', performSearch);
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
        addOrderBtn.addEventListener('click', showAddOrderModal);
        closeModalBtn.addEventListener('click', hideOrderModal);
        cancelModalBtn.addEventListener('click', hideOrderModal);
        orderForm.addEventListener('submit', handleOrderSubmit);
        imageUpload.addEventListener('change', handleImageUpload);
        
        // 侧边栏菜单点击事件
        menuItems.forEach(item => {
            item.addEventListener('click', function() {
                const page = this.getAttribute('data-page');
                navigateToPage(page);
            });
        });
        
        // 页面导航函数
        function navigateToPage(page) {
            if (page === 'order') {
                window.location.href = 'order.html';
            } else if (page === 'employees') {
                window.location.href = 'employees.html';
            } else if (page === 'dashboard') {
                window.location.href = 'dashboard.html';
            } else if (page === 'login') {
                window.location.href = 'index.html';
            } else if (page === 'activities') {
                window.location.href = 'activities.html';
            } else if (page === 'settings') {
                window.location.href = 'settings.html';
            } else if (page === 'ai-chat') {
                window.location.href = 'ai-chat.html';
            } else if(page === 'expert'){
                window.location.href = 'expert.html';
            } else if(page === 'product'){
                window.location.href = 'product.html';
            }else if(page === 'farm-management'){
                window.location.href = 'farm.html';
            }
        }
        
        // 初始化页面
        function initPage() {
            setActiveMenuItem();
            loadOrders();
        }
        
        // 加载订单数据
        function loadOrders() {
            showLoading();
            
            // 构建查询参数
            const params = {
                page: currentOrderPage,
                pageSize: pageSize,
                name: searchKeyword
            };
            
            fetch(`${BASE_URL}/admin/order/page?${new URLSearchParams(params)}`, {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
                .then(response => response.json())
                .then(data => {
                    console.log('订单数据:', data);
                    if (data.code === 1) {
                        renderOrders(data.data);
                        updatePaginationInfo();
                    } else {
                        alert('加载订单数据失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('加载订单数据时出错');
                })
                .finally(() => {
                    hideLoading();
                });
        }
        
        // 渲染订单表格
        function renderOrders(pageResult) {
            orderTable.innerHTML = '';
            
            if (!pageResult || !pageResult.records || pageResult.records.length === 0) {
                const row = orderTable.insertRow();
                const cell = row.insertCell(0);
                cell.colSpan = 9;
                cell.textContent = '没有找到订单数据';
                cell.style.textAlign = 'center';
                return;
            }
            
            pageResult.records.forEach(order => {
                const row = orderTable.insertRow();
                
                // ID
                const idCell = row.insertCell(0);
                idCell.textContent = order.id;
                
                // 产品图片
                const imageCell = row.insertCell(1);
                if (order.picture) {
                    const img = document.createElement('img');
                    img.src = order.picture;
                    img.alt = order.name;
                    img.className = 'order-image';
                    imageCell.appendChild(img);
                } else {
                    imageCell.innerHTML = '<i class="fas fa-image" style="color: #ccc;"></i>';
                }
                
                // 产品名称
                const nameCell = row.insertCell(2);
                nameCell.textContent = order.name || '-';
                
                // 商家名称
                const storeCell = row.insertCell(3);
                storeCell.textContent = order.storeName || '-';
                
                // 用户ID
                const userCell = row.insertCell(4);
                userCell.textContent = order.userId || '-';
                
                // 数量
                const numCell = row.insertCell(5);
                numCell.textContent = order.number || '0';
                
                // 单价
                const priceCell = row.insertCell(6);
                priceCell.textContent = order.price ? `¥${order.price.toFixed(2)}` : '-';
                
                // 状态
                const statusCell = row.insertCell(7);
                const statusBadge = document.createElement('span');
                statusBadge.className = `status-badge status-${order.status}`;
                statusBadge.textContent = order.status === 1 ? '已完成' : '未完成';
                statusCell.appendChild(statusBadge);
                
                // 操作
                const actionCell = row.insertCell(8);
                const editBtn = document.createElement('button');
                editBtn.className = 'action-btn edit-btn';
                editBtn.innerHTML = '<i class="fas fa-edit"></i> 编辑';
                editBtn.addEventListener('click', () => showEditOrderModal(order));
                
                const deleteBtn = document.createElement('button');
                deleteBtn.className = 'action-btn delete-btn';
                deleteBtn.innerHTML = '<i class="fas fa-trash-alt"></i> 删除';
                deleteBtn.addEventListener('click', () => confirmDeleteOrder(order.id));
                
                actionCell.appendChild(editBtn);
                actionCell.appendChild(deleteBtn);
            });
        }
        
        // 更新分页信息
        function updatePaginationInfo() {
            currentPageSpan.textContent = `第 ${currentOrderPage} 页`;
            
            // 禁用/启用上一页/下一页按钮
            prevPageBtn.disabled = currentOrderPage <= 1;
            nextPageBtn.disabled = false; // 这里需要根据实际数据调整
        }
        
        // 上一页
        function goToPrevPage() {
            if (currentOrderPage > 1) {
                currentOrderPage--;
                loadOrders();
            }
        }
        
        // 下一页
        function goToNextPage() {
            currentOrderPage++;
            loadOrders();
        }
        
        // 改变每页显示数量
        function changePageSize() {
            pageSize = parseInt(pageSizeSelect.value);
            currentOrderPage = 1;
            loadOrders();
        }
        
        // 执行搜索
        function performSearch() {
            searchKeyword = searchInput.value.trim();
            currentOrderPage = 1;
            loadOrders();
        }
        
        // 显示加载中
        function showLoading() {
            loadingOverlay.style.display = 'flex';
        }
        
        // 隐藏加载中
        function hideLoading() {
            loadingOverlay.style.display = 'none';
        }
        
        // 显示新增订单模态框
        function showAddOrderModal() {
            modalTitle.textContent = '新增订单';
            orderForm.reset();
            document.getElementById('orderId').value = '';
            imagePreview.innerHTML = '<i class="fas fa-image" style="font-size: 24px; color: #ccc;"></i>';
            pictureInput.value = '';
            orderModal.style.display = 'flex';
        }
        
        // 显示编辑订单模态框
        function showEditOrderModal(order) {
            modalTitle.textContent = '编辑订单';
            document.getElementById('orderId').value = order.id || '';
            document.getElementById('modalProductName').value = order.name || '';
            document.getElementById('modalStoreName').value = order.storeName || '';
            document.getElementById('modalUserId').value = order.userId || '';
            document.getElementById('modalType').value = order.type || '';
            document.getElementById('modalNumber').value = order.number || '';
            document.getElementById('modalPrice').value = order.price || '';
            document.getElementById('modalAddress').value = order.address || '';
            document.getElementById('modalStatus').value = order.status || '0';
            pictureInput.value = order.picture || '';
            
            // 设置图片预览
            if (order.picture) {
                imagePreview.innerHTML = `<img src="${order.picture}" alt="${order.name}">`;
            } else {
                imagePreview.innerHTML = '<i class="fas fa-image" style="font-size: 24px; color: #ccc;"></i>';
            }
            
            orderModal.style.display = 'flex';
        }
        
        // 隐藏订单模态框
        function hideOrderModal() {
            orderModal.style.display = 'none';
        }
        
        // 处理图片上传
        function handleImageUpload(e) {
            const file = e.target.files[0];
            if (!file) return;
            
            // 验证文件类型和大小
            if (!file.type.match('image.*')) {
                alert('请选择图片文件');
                return;
            }
            
            if (file.size > 2 * 1024 * 1024) {
                alert('图片大小不能超过2MB');
                return;
            }
            
            // 显示预览
            const reader = new FileReader();
            reader.onload = function(e) {
                imagePreview.innerHTML = `<img src="${e.target.result}" alt="预览">`;
            };
            reader.readAsDataURL(file);
            
            // 上传到OSS
            uploadImageToOSS(file);
        }
        
        // 上传图片到OSS
        function uploadImageToOSS(file) {
            showLoading();
            
            const formData = new FormData();
            formData.append('file', file);
            
            fetch(OSS_UPLOAD_URL, {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                console.log('OSS上传返回:', data);
                if (data.code === 1) {
                    // 假设返回数据中有url字段
                    pictureInput.value = data.data.url || '';
                    console.log('图片URL已设置:', pictureInput.value);
                } else {
                    alert('图片上传失败: ' + data.msg);
                    imagePreview.innerHTML = '<i class="fas fa-image" style="font-size: 24px; color: #ccc;"></i>';
                }
            })
            .catch(error => {
                console.error('上传错误:', error);
                alert('图片上传时出错');
                imagePreview.innerHTML = '<i class="fas fa-image" style="font-size: 24px; color: #ccc;"></i>';
            })
            .finally(() => {
                hideLoading();
            });
        }
        
        // 处理订单表单提交
        function handleOrderSubmit(e) {
            e.preventDefault();
            
            const orderId = document.getElementById('orderId').value;
            const isEdit = !!orderId;
            
            const orderData = {
                name: document.getElementById('modalProductName').value.trim(),
                storeName: document.getElementById('modalStoreName').value.trim(),
                userId: document.getElementById('modalUserId').value.trim(),
                type: document.getElementById('modalType').value.trim(),
                number: parseInt(document.getElementById('modalNumber').value),
                price: parseFloat(document.getElementById('modalPrice').value),
                address: document.getElementById('modalAddress').value.trim(),
                status: parseInt(document.getElementById('modalStatus').value),
                picture: pictureInput.value
            };
            
            console.log('提交的订单数据:', orderData);
            
            if (isEdit) {
                orderData.id = orderId;
                updateOrder(orderData);
            } else {
                addOrder(orderData);
            }
        }
        
        // 添加订单
        function addOrder(orderData) {
            showLoading();
            
            fetch(`${BASE_URL}/admin/order`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(orderData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    alert('订单添加成功');
                    hideOrderModal();
                    loadOrders();
                } else {
                    alert('添加订单失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('添加订单时出错');
            })
            .finally(() => {
                hideLoading();
            });
        }
        
        // 更新订单
        function updateOrder(orderData) {
            showLoading();
            const orderId = document.getElementById('orderId').value;
            
            fetch(`${BASE_URL}/admin/order/${orderId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(orderData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    alert('订单更新成功');
                    hideOrderModal();
                    loadOrders();
                } else {
                    alert('更新订单失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新订单时出错');
            })
            .finally(() => {
                hideLoading();
            });
        }
        
        // 确认删除订单
        function confirmDeleteOrder(orderId) {
            if (confirm('确定要删除这个订单吗？此操作不可恢复。')) {
                deleteOrder(orderId);
            }
        }
        
        // 删除订单
        function deleteOrder(id) {
            showLoading();
            fetch(`${BASE_URL}/admin/order/${id}`, {
                method: 'DELETE',
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    alert('订单删除成功');
                    loadOrders();
                } else {
                    alert('删除订单失败: ' + data.msg);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('删除订单时出错');
            })
            .finally(() => {
                hideLoading();
            });
        }

        function setActiveMenuItem() {
            const currentPage = window.location.pathname.split('/').pop().replace('.html', '');
            document.querySelectorAll('.sidebar-menu li').forEach(item => {
                item.classList.remove('active');
                if (item.getAttribute('data-page') === currentPage) {
                    item.classList.add('active');
                }
            });
        }
    });
</script>
</body>
</html>